<style lang="scss" scoped>
.infos-box {
  .avatar-upload {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar {
    width: 2.44rem;
    height: 2.44rem;
    background-color: #fff;
    border-radius: 50%;
    margin: .2rem auto;
    position: relative;

    >img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }

    .edit {
      position: absolute;
      right: 0;
      top: .4rem;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .submit {
    margin: .2rem;
  }
}

.modal-box {
  padding: .2rem .4rem;

  input,
  textarea {
    padding: .2rem;
    outline: none;
    border: 1px solid #e9e9e9;
    background-color: #fff;
    border-radius: 4px;
    width: 100%;
    min-height: .64rem;
  }
}
</style>

<template>
  <div class="container hasNav">
    <van-nav-bar title="个人资料" left-arrow left-text="返回" @click-left="$router.back()" fixed />
    <div class="infos-box">
      <div class="avatar-upload">
        <van-uploader :after-read="afterAvatarRead" :max-size="5 * 1024 * 1024">
          <div class="avatar">
            <img :src="form.avatar" v-if="form.avatar">
            <div class="edit">
              <van-icon name="edit" color="#d24a58" size="24" />
            </div>
          </div>
        </van-uploader>
      </div>
      <div class="cells">
        <van-cell title="姓名" :value="form.username" @click="showModalEvent(0)" is-link />
        <van-cell title="性别" :value="genderName" @click="showGenderEvent" is-link />
        <van-cell title="出生日期" :value="`${!!form.birthday ? $moment(form.birthday).format('YYYY年MM月DD日') : '未填写'}`"
          @click="showBirthEvent" is-link />
        <van-cell title="简介" :value="form.introduction" @click="showModalEvent(1)" is-link />
      </div>
      <div class="submit">
        <van-button block type="default" color="#d24a58" @click="onSubmit">保存</van-button>
      </div>
    </div>
    <!-- 填写姓名、简介 -->
    <van-dialog v-model="showModal" :title="`请填写${modalTitle}`" @confirm="handleModalConfirm" @open="handleModalOpen"
      @close="handleModalClose" show-cancel-button>
      <div class="modal-box">
        <template v-if="modalType === 0">
          <input type="text" v-model="modalValue" maxlength="20" placeholder="请填写姓名">
        </template>
        <template v-if="modalType === 1">
          <textarea v-model="modalValue" cols="30" rows="10" maxlength="1000" placeholder="请填写简介，最多1000字。"></textarea>
        </template>
      </div>
    </van-dialog>
    <!-- 选择性别 -->
    <van-action-sheet v-model="showGender" :actions="genders" cancel-text="取消" close-on-click-action
      @select="onGenderSelect" />

    <!-- 选择出生年月日 -->
    <van-popup v-model="showBirth" position="bottom">
      <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate" @confirm="onBirthConfirm"
        @cancel="showBirth = false" v-model="currentDate" :formatter="dateFormat" />
    </van-popup>
    <Loading :isShow="loading"></Loading>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Loading from '@/components/Loading';
import { fileUrl, saveUserAvatar, saveUserInfo, getUserInfo } from "../../api/user";

function isNull(val) {
  return val === '' || !val
}

export default {
  name: 'UserInfos',
  components: {
    Loading,
  },
  data() {
    return {
      loading: true,
      showModal: false,
      showGender: false,
      showBirth: false,
      genders: [
        { name: '男', value: 1 },
        { name: '女', value: 2 }
      ],
      modalType: 0, // 0 姓名 1 简介
      currentDate: new Date(),
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2050, 0, 1),
      form: {
        avatar: null,
        username: null,
        gender: 1,
        birthday: null,
        introduction: null
      },
      genderName: '',
      modalValue: ''
    };
  },
  mounted() {
    this.getDetail();
  },
  computed: {
    ...mapGetters(['userInfo']),
    modalTitle() {
      return this.modalType === 1 ? '简介' : '姓名'
    }
  },
  methods: {
    async getDetail() {
      try {
        this.loading = true;
        const { code, message, data } = await getUserInfo();
        if (code == 200) {
          this.form.avatar = fileUrl + data.headPic
          this.form.username = !isNull(data.username) ? data.username : ''
          this.form.gender = +data.gender
          this.form.genderName = this.genderName = +data.gender === 1 ? '男' : +data.gender === 2 ? '女' : '未知'
          this.form.birthday = !isNull(data.birthday) ? data.birthday : ''
          this.form.introduction = !isNull(data.introduction) ? data.introduction : ''
          this.currentDate = !isNull(data.birthday) ? new Date(data.birthday) : new Date()
          let userInfo = JSON.parse(JSON.stringify(this.userInfo))
          this.$store.commit('setUserInfo', userInfo);
        } else {
          this.$toast(message);
        }
        this.$nextTick(() => {
          this.loading = false;
        });
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    },
    showModalEvent(index) {
      this.showModal = true;
      this.modalType = index;
    },
    showGenderEvent() {
      this.showGender = true;
    },
    showBirthEvent() {
      this.showBirth = true;
    },
    onGenderSelect(item) {
      this.form.gender = item.value;
      this.form.genderName = item.name
      this.genderName = item.name
    },
    onBirthConfirm(date) {
      this.showBirth = false;
      this.form.birthday = this.$moment(date).format('YYYY-MM-DD')
    },
    dateFormat(type, val) {
      if (type === 'year') {
        return val + '年';
      }
      if (type === 'month') {
        return val + '月';
      }
      if (type === 'day') {
        return val + '日';
      }
      return val;
    },
    async afterAvatarRead(file) {
      let formData = new FormData();
      formData.append('file', file.file)
      const { code, message, data } = await saveUserAvatar(formData)
      if (code == 200) {
        this.form.avatar = fileUrl + data
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        userInfo.user.headPic = data
        this.$store.commit('setUserInfo', userInfo)
        this.$toast('修改头像成功!')
      } else {
        this.$toast(message)
      }
    },
    handleModalConfirm() {
      let keyName = ['username', 'introduction']
      if (isNull(this.modalValue)) {
        this.$toast('内容不能为空')
        return
      }
      this.form[keyName[this.modalType]] = this.modalValue;
    },
    handleModalOpen() {
      let keyName = ['username', 'introduction']
      this.modalValue = this.form[keyName[this.modalType]]
    },
    handleModalClose() {
      this.modalValue = '';
    },
    async onSubmit() {
      let formData = new FormData();
      if (isNull(this.form.username) || isNull(this.form.gender) || isNull(this.form.birthday)) {
        this.$toast('必须填写姓名、性别和生日')
        return
      }
      formData.append('username', this.form.username);
      formData.append('gender', this.form.gender);
      formData.append('birthday', this.form.birthday);
      formData.append('introduction', this.form.introduction);
      const { code, message } = await saveUserInfo(formData)
      if (code == 200) {
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        userInfo.user.username = this.form.username
        userInfo.user.gender = this.form.gender
        userInfo.user.birthday = this.form.birthday
        userInfo.user.introduction = this.form.introduction
        this.$store.commit('setUserInfo', userInfo)
        this.$toast('保存成功')
      } else {
        this.$toast(message)
      }
    }
  }
};
</script>
